import axios from 'axios'
const merge = require('webpack-merge')
let config = process.env;
let access_token = sessionStorage.getItem("token");
let Api = {
  authLogin: "auth/login"
};

export default {
  post (apiKey, data = {}, headers = {}) {
    return new Promise((resolve,reject)=>{
      axios({
        method: 'post',
        url: config.API_ROOT+Api[apiKey],
        data: JSON.stringify(data),
        timeout: 0,
        headers:merge({
          "content-type":"application/json",
          "version":config.version,
          "token":getToken()
        },headers)
      })
      .then((d)=>{
        if(d.status == 200){
          if (d.data.code == 1011 || d.data.code == 1012){
            window.location = '/#/';
          }else{
            resolve(d.data);
          }
        }else{
          reject(d);
        }
      })
      .catch((e)=>{
        reject(e);
      })
    })
  },
  get (apiKey, data, headers){
    data.token = getToken();
    return new Promise((resolve,reject)=>{
      axios({
        method: 'get',
        url: config.API_ROOT+Api[apiKey]+formartBody(data),
        timeout: 0,
        headers:merge({
          "content-type":"application/json",
          "version":config.version,
        },headers)
      })
      .then((d)=>{
        if(d.status == 200){
          if (d.data.code == 1011 || d.data.code == 1012){
            window.location = '/#/';
          }else{
            resolve(d.data);
          }
        }else{ 
          reject(d);
        }
      })
      .catch((e) => {
        reject(e);
      })
    })
  }
}

function formartBody(body){
  if(
      (typeof body == 'object' || typeof body == 'string')
      && !Array.isArray(body)
  ){
      let kvs = [];
      for(var key in body){
          kvs.push(key+"="+body[key]);
      }
      let querystring = kvs.join("&");
      return `?${querystring}`;
  }else {
      throw new Error("body only [Object] or [String]");
  }
}

export function getToken(){
  //TODO
  return localStorage.getItem("access_token");
  // return new Promise((resolve,reject)=>{
  //   resolve("token");
  // });
}

export function addApi(api){
  Api = Object.assign(Api,api);
}